package com.ie.sevice.before;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ie.comment.http.ResponseResult;
import com.ie.comment.sercurity.utiles.ConfigrarionBean;
import com.ie.comment.sercurity.utiles.JwtTokenUtil;
import com.ie.comment.sercurity.utiles.MD5Util;
import com.ie.comment.sercurity.utiles.RedisUtil;
import com.ie.entity.BUserEntity;
import com.ie.mapper.before.BUserMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author hp
 */
@Service
public class BUserServiceImpl extends ServiceImpl<BUserMapper, BUserEntity> implements BUserService {

    @Autowired
    private RedisUtil  redisUtil;

    @Autowired
    private JwtTokenUtil jwtTokenUtil;

    @Autowired
    private ConfigrarionBean config;

    //判断账号是否存在，如果存在就不处理，不存在就注册一个
    @Override
    public ResponseResult<Map<String, String>> register(BUserEntity bUserEntity) {
        bUserEntity.setBpwd(MD5Util.MD5(bUserEntity.getBpwd()));
        Long count = lambdaQuery().eq(BUserEntity::getBemail, bUserEntity.getBemail()).count();
        if (count > 0){
            return ResponseResult.getMessageResult(null,"A001");
        } else if (save(bUserEntity)) {
            return ResponseResult.getMessageResult(null,"A002");
        }else {
            return ResponseResult.getMessageResult(null,"A003");
        }

    }

    @Override
    public ResponseResult<Map<String, String>> login(BUserEntity bUserEntity) {
//        String code = (String) redisUtil.get("code");
//        //验证码错误
//        if(!code.equalsIgnoreCase(bUserEntity.getCode())){
//            return ResponseResult.getMessageResult(null,"A000");
//        }
        //查看用户是否存在
        Long count = lambdaQuery().eq(BUserEntity::getBemail , bUserEntity.getBemail()).count();
        //账号不存在
        if (count == 0){
            return ResponseResult.getMessageResult(null,"A001");
        }
//        bUserEntity.setBpwd(MD5Util.MD5(bUserEntity.getBpwd()));
        List<BUserEntity> list = lambdaQuery()
                .eq(BUserEntity::getBemail, bUserEntity.getBemail())
                .eq(BUserEntity::getBpwd, MD5Util.MD5(bUserEntity.getBpwd())).list();

        if (list.size() > 0){
            String token = jwtTokenUtil.createToken(bUserEntity.getBemail());
            redisUtil.set("login_"+bUserEntity.getBemail(), bUserEntity.getBemail() , config.getRedisExpiration());
            HashMap<String , String> myres = new HashMap<>();
            myres.put("buserauthtoken",token);
            myres.put("bemail",bUserEntity.getBemail());
            myres.put("bid", list.get(0)+"");
            return ResponseResult.getSuccessResult(myres);
        }else {
            return ResponseResult.getMessageResult(null,"A003");
        }

    }
}